<template>
  <el-dropdown>
    <span class="el-dropdown-link">
      <el-avatar :size="40" :src="squareUrl" shape="square"/>
        &nbsp;&nbsp;{{ currentUser.username }}
        <el-icon class="el-icon--right">
          <arrow-down/>
        </el-icon>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="userCenter">个人中心</el-dropdown-item>
        <el-dropdown-item @click="logout">安全退出</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script lang="ts" setup>
import {ArrowDown} from '@element-plus/icons-vue/dist'
import {reactive, ref, watch} from 'vue'
import store from '@/store'
import * as request from "@/utils/request";
import {ElMessage, ElMessageBox} from "element-plus";
import router from "@/router";
import {doLogout} from "@/api/login";
interface CurrentUser{
  username:string;
  avatar:string;
}
const currentUser = reactive<CurrentUser>(store.getters.GET_USER_INFO);
const squareUrl = ref<string>(request.getServerUrl() +"/image/userAvatar/"+ currentUser.avatar)
const logout = () => {
  ElMessageBox.confirm(
      '确定要退出吗?',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const res: any = await doLogout();
        const {data, code} = res.data;
        console.log(data)
        if (code === 200) {
          store.commit('SET_ROUTES_STATE', false)
          store.commit('RESET_TABS')
          await store.dispatch('logout')
          ElMessage({
            type: 'success',
            message: '退出登录成功!',
          })
        }


      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消成功!',
        })
      })


}
const userCenter = () => {
  router.push('/userCenter')
}
//监听store中userinfo的值
watch(store.getters.GET_USER_INFO, (newVal: CurrentUser) => {
  currentUser.username = newVal.username;
  currentUser.avatar = newVal.avatar;
  squareUrl.value = request.getServerUrl() +"/image/userAvatar/"+ currentUser.avatar
})
</script>

<style lang="scss" scoped>
.el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
</style>